<template>
	<view class="creategoxy">
		<view class="flex c9" @click="openInput()">
			<u-icon name="plus" color="#999" size="18"></u-icon>
			新增分类
		</view>
		<view class="cellList" v-for="(i, index) in list" :key="i._id">
			<view class="cell">
				<view>{{ i.name }}</view>
				<view class="flex">
					<u-icon name="edit-pen" color="red" size="18" class="mgr20" @click="updateData(index)"></u-icon>
					<u-icon name="trash" color="red" size="18" @click="deleteData(index)"></u-icon>
				</view>
			</view>
		</view>
		<!-- 提示信息弹窗 -->
		<uni-popup ref="inputLoading" type="dialog">
			<uni-popup-dialog mode="input" title="分类名称" @confirm="dialogConfirm" v-model="popupValue" @close="popupValue = ''"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue';
const list = reactive([]);

let popupValue = ref('');
const inputLoading = ref();
// 打开输入框
const openInput = () => {
	inputLoading.value.open();
};
//获取数据
const cuObj = uniCloud.importObject('mall-categories');
const getData = async () => {
	let res = await cuObj.get();
	console.log(res.data);
	if (!res?.data.length) return;
	res.data.map((i) => {
		list.push(i);
	});
};
// 添加 or 修改
const dialogConfirm = async (e) => {
	if (updataId.value != null) {
		// await db.collection('mall-categories').doc(list[updataId.value]._id).update({
		//     name: e
		// });
		await cuObj.update(list[updataId.value]._id, e);
		list[updataId.value].name = e;
	} else {
		let data = {
			name: e,
			is_show: true
		};
		let res = await cuObj.add(data);
		data._id = res.id;
		list.push(data);
	}
	updataId.value = null;
	popupValue.value = '';
};
//删除
const deleteData = (index) => {
	list[index]._id;
	uni.showModal({
		title: '您是否要删除?',
		async success() {
			await cuObj.delete(list[index]._id);
			list.splice(index, 1);
		}
	});
};
// 修改
const updataId = ref();
const updateData = (index) => {
	popupValue.value = list[index].name;
	updataId.value = index;
	openInput();
};
onMounted(() => {
	getData();
});
</script>

<style scoped lang="scss">
.creategoxy {
	background-color: #fff;
	height: 91vh;
	padding: 25rpx;
	box-sizing: border-box;
	font-size: $uni-font-size-paragraph;

	.cellList {
		.cell {
			@include flex-box();
			padding: 20rpx 0;
		}

		&:not(:last-child) {
			border-bottom: 1px solid #eee;
		}

		&:last-child {
			border-bottom: none;
		}
	}
}

.dialog {
	background-color: #f8f8f8;
	padding: 10rpx 20rpx;
	font-size: 28rpx;
}
</style>
